package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zhihu/api/request"
	"zhihu/inter/dao"
	"zhihu/inter/model"
)

func CreateEssay(c *gin.Context) {
	var req request.EssayCreate
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var essay model.Essoys
	dao.GetOneByFields(&model.Essoys{}, &essay)
	if essay.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "此文章已存在",
			"data": nil,
		})
		return
	}
	if essay.Title == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "标题不能为空",
			"data": nil,
		})
		return
	}
	essay = model.Essoys{
		Title:  req.Title,
		Image:  req.Image,
		Author: req.Author,
	}
	if !dao.Create(&essay) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "发布失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": essay,
	})
}

func CreateComment(c *gin.Context) {
	var req request.ComCreate
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var com model.Comments
	dao.GetOneByFields(&model.Comments{}, &com)
	if com.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "此评论已存在",
			"data": nil,
		})
		return
	}
	com = model.Comments{
		EssayId: req.EssayId,
		Comment: req.Comment,
	}
	if !dao.Create(&com) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "评论发布失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "发布成功",
		"data": com,
	})
}

func FindComment(c *gin.Context) {
	var com []model.Comments
	dao.GetListByFields(&model.Comments{}, &com)
	var coms []*model.Comments
	for _, v := range com {
		coms = append(coms, &v)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "评论查询成功",
		"data": nil,
	})
}
